<!-- 影像号维护 -->
<template>
  <div class="ky-container">
    <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
      <el-form ref="formSearch" :model="formData" :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="83px">
        <el-form-item label="医院名称" prop="hospitalCode">
          <el-select
            size="small"
            class="param-type_input"
            filterable
            v-model="formData.hospitalCode"
            placeholder="请选择"
            @change="hospitalChange">
            <el-option
              v-for="(item,index) in mx_hospitalList"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover" class="ky-card ky-card-hdbg ky-mt10">
      <div class="image-content">
        <div class="image-main">
          <div class="title">影像号维护</div>
          <el-table
            ref="table"
            v-loading="loading"
            size="medium"
            :data="tableData"
            style="width: 100%"
            border
            class="ky-table"
            @selection-change="handleSelectionChange"
            highlight-current-row
          >
            <el-table-column type="selection" width="40" label="选择"></el-table-column>
            <el-table-column align="left" label="操作" v-if="$hasPermission(['YJYY10005012','YJYY10005013'])" width="170">
              <template slot-scope="scope">
                <div class="flex flex-row justify-center text-center">
                  <el-button type="primary" size="small" v-permission="'YJYY10005012'" @click="openEditor(scope.row)"><i class="el-icon-edit"></i> 编辑</el-button>
                  <el-button type="danger" size="small" v-permission="'YJYY10005013'" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column align="left" prop="ID" label="ID"></el-table-column> -->
            <el-table-column align="left" prop="hospitalCode" label="医院代码" width="176px" show-overflow-tooltip></el-table-column>
            <el-table-column align="left" prop="hospitalCode" label="医院名称" :formatter="frtHospCode" width="170px" show-overflow-tooltip></el-table-column>
            <el-table-column align="left" prop="dep" label="检查部门" show-overflow-tooltip> </el-table-column>
            <el-table-column align="left" prop="modality" label="设备类型" show-overflow-tooltip></el-table-column>
            <el-table-column align="left" prop="charFlag" label="前缀符号"></el-table-column>
            <el-table-column align="left" prop="streamId" label="影像号序号" width="98px"></el-table-column>
            <el-table-column align="left" prop="streamDate" label="影像号生成时间" width="162px"></el-table-column>
          </el-table>
          <paginationCont
            :total="totalCount"
            :page.sync="currentPage"
            :limit.sync="pageSize"
            @pagination="changePagenation"
          />
        </div>
        <transition name="fade-form" mode="out-in">
          <div :class="{'toolBox-small':device !== 'mobile' && sidebar.opened,'toolBox-midul': device !== 'mobile' && !sidebar.opened,'toolBox-large':device == 'mobile','toolBox':true}" v-show="showToolBox">
            <div>
              <i class="el-icon-info icon blue-color"></i>
              <span class="toolBox-text">已选择<span class="blue-color">{{multipleSelection.length}}</span>项</span>
              <span class="cancle-click" @click="cancleChoose">取消选择</span>
            </div>
            <div>
              <el-button type="danger" size="small" v-permission="'YJYY10005013'" @click="batchDelete">批量删除</el-button>
            </div>
          </div>
        </transition>
        <div class="right-panel">
          <div class="panel-head">
            <div class="title">{{currentStatus === pageStatus.add ? '添加':'编辑'}}</div>
            <div class="blue-color" @click="addClick" v-permission="'YJYY10005014'" v-show="currentStatus === pageStatus.edit"><i class="el-icon-plus icon"></i>新增</div>
          </div>
          <el-form inline class="rule-form" ref="form" :model="ruleForm" :rules="rules">
            <el-form-item label="医院名称:" prop="hospitalCode">
              <el-select
                size="small"
                class="param-type_input"
                filterable
                :disabled="currentStatus === pageStatus.edit"
                v-model="ruleForm.hospitalCode"
                placeholder="请选择"
                @change="handleChange('hospital')">
                <el-option
                  v-for="(item,index) in mx_hospitalList"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查部门:" prop="dep" class="short-input">
              <el-select size="small" class="param-type_input" v-model="ruleForm.dep" placeholder="请选择" clearable collapse-tags @change="handleChange('dep')">
                <el-option
                  v-for="(item,index) in depOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备类型:" prop="modality" class="short-input">
              <el-select size="small" class="param-type_input" v-model="ruleForm.modality" :disabled="ruleForm.dep === 'ALL'" placeholder="请选择" clearable collapse-tags>
                <el-option
                  v-for="(item,index) in modalityOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="前缀符号:" prop="charFlag" class="short-input">
              <el-input size="small" v-model="ruleForm.charFlag" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="检查号序号:" prop="streamId" class="short-input">
              <el-input size="small" v-model.number="ruleForm.streamId" placeholder="请输入"></el-input>
            </el-form-item>
            <!-- <el-form-item label="初始号码:" prop="startNumber" class="short-input">
                <el-input size="small" v-model="ruleForm.startNumber" placeholder="请输入"></el-input>
                </el-form-item> -->
            <el-form-item class="buttons">
              <el-button class="m-l-1" type="primary" size="small" @click="handleConfirm">保存</el-button>
              <el-button v-if="currentStatus === pageStatus.add" class="m-l-1" size="small" @click="handleCancle">取消</el-button>
              <el-button v-else class="m-l-1" size="small" v-permission="'YJYY10005013'" type="danger" plain @click="handleDelete(ruleForm.id,ruleForm.hospitalCode)">删除</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getModalityTypeList, getDepList, getXnoPages, setXnoPages, updateXnoPages, deleteXnoPages } from '@/api/api.js'
import { PageStatus } from '@/utils/constant'
import paginationCont from '@/components/Pagination/index'
export default {
  name: '',
  components: { paginationCont },
  data() {
    return {
      showToolBox: false,
      pageStatus: PageStatus,
      currentStatus: PageStatus.add,
      loading: false,
      tableData: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      multipleSelection: [],
      depOptions: [],
      modalityOptions: [],
      ruleForm: {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        modality: '',
        charFlag: '',
        startNumber: '',
        streamId: null
      },
      rules: {
        dep: { required: true, message: '请选择检查部门', trigger: ['blur', 'change'] },
        //  modality: { required: true, message: '请选择设备类型', trigger: ['blur', 'change'] },
        // charFlag: { required: true, message: '请填写前缀符号', trigger: 'blur' },
        streamId: { required: true, message: '请填写影像号序号', trigger: 'blur' }
      },
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode
      }
    }
  },
  watch: {
    multipleSelection(val) {
      if (val && val.length > 1) {
        this.showToolBox = true
      } else {
        this.showToolBox = false
      }
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    }
  },
  created() {
    this.$getHospitalList()
  },
  mounted() {
    this.getScheduledDepOptions()
    this.getScheduledModalityOptions()
    this.search()
  },
  methods: {
    hospitalChange() {
      this.ruleForm.hospitalCode = this.formData.hospitalCode
      this.handleChange('hospital')
      this.search()
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.currentStatus === this.pageStatus.add) {
            setXnoPages(this.ruleForm).then((res) => {
              if (res.code === 10000) {
                this.$message.success('保存成功')
                this.changePagenation()
                this.handleReset()
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            updateXnoPages(this.ruleForm).then((res) => {
              if (res.code === 10000) {
                this.$message.success('修改成功')
                this.changePagenation()
                this.handleReset()
                this.currentStatus = this.pageStatus.add
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
        }
      })
    },
    handleCancle() {
      this.handleReset()
    },
    handleReset() {
      let hcode = ''
      if (this.ruleForm.hospitalCode !== this.formData.hospitalCode) {
        hcode = this.formData.hospitalCode
      }
      this.$refs.form.resetFields()
      this.$nextTick(() => {
        if (hcode) {
          this.ruleForm.hospitalCode = hcode
          this.handleChange('hospital')
        }
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.ruleForm.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            this.depOptions.unshift('ALL')
            resolve(res)
          }
        })
      })
    },
    getScheduledModalityOptions() {
      /* 设备类型列表 */
      let params = {
        hospitalCode: this.ruleForm.hospitalCode,
        dep: this.ruleForm.dep
      }
      return new Promise(async resolve => {
        await getModalityTypeList(params).then((res) => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depOptions = []
          this.modalityOptions = []
          this.ruleForm.dep = ''
          this.ruleForm.modality = ''

          try {
            await this.getScheduledDepOptions()
            await this.getScheduledModalityOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'dep':
          this.modalityOptions = []
          this.ruleForm.modality = ''
          this.ruleForm.dep !== 'ALL' && this.getScheduledModalityOptions()
          break
        default:
          break
      }
    },
    async openEditor(row) {
      /* 编辑 */
      this.currentStatus = this.pageStatus.edit
      this.ruleForm = Object.assign(this.ruleForm, row)
      try {
        await this.getScheduledDepOptions()
        await this.getScheduledModalityOptions()
      } catch (err) {
        console.log(err)
      }
    },
    handleDelete(row) {
      /* 删除 */
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteXnoPages({ id: row.id, hospitalCode: row.hospitalCode }).then((res) => {
          if (res.code === 10000) {
            this.$message.success('删除成功')
            this.changePagenation()
            this.handleReset()
            this.currentStatus = this.pageStatus.add
          }
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addClick() {
      this.currentStatus = this.pageStatus.add
      this.handleReset()
      this.getScheduledModalityOptions()
    },
    fetchData() {
      this.loading = true
      let data = {
        HospitalCode: this.formData.hospitalCode,
        pageSize: this.pageSize,
        pageNumber: this.currentPage
      }
      getXnoPages(data).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
        } else {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
        }
      }).catch(() => {
        this.loading = false
      })
    },
    changePagenation() {
      this.fetchData()
    },
    search() {
      // 查询
      this.$refs.formSearch.validate((valid) => {
        if (valid) {
          this.currentPage = 1
          this.fetchData()
        }
      })
    },
    // 格式化医院code
    frtHospCode(row, column, cellValue, index) {
      let name = ''
      let hospIndex = this.mx_hospitalList.findIndex(item => item.code === cellValue)
      if (hospIndex !== -1) {
        name = this.mx_hospitalList[hospIndex].name
      }
      return name
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    cancleChoose() {
      // 取消选择
      this.multipleSelection = []
      this.$refs.table.clearSelection()
    },
    batchDelete() {
      // 批量删除
      let confirmMsg = '此操作将永久批量删除该选中影响号, 是否继续?'
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let successNum = 0
        let faliNum = 0
        for (let v of this.multipleSelection) {
          let data = {
            id: v.id,
            hospitalCode: v.hospitalCode
          }
          await deleteXnoPages(data).then((res) => {
            if (res && res.code === 10000) {
              successNum++
            } else {
              faliNum++
            }
          }).catch(() => {

          })
        }
        this.changePagination()
        this.$message.success(`已经成功删除` + successNum + '条,失败' + faliNum + '条')

        // 本地缓存排班管理的机房选择数据重置默认选项
        // this.$store.dispatch('user/getDefaultCheckRoomTree')
        // this.$store.dispatch('user/resetDefaultCheckRoom', [])
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  beforeDestroy() {},
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.image-content{
    display: flex;
    .title{
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        margin-bottom: 15px;
    }
    .image-main{
        width:calc(100% - 250px);
        padding:20px
    }
    .right-panel{
            width:250px;
            padding: 20px;
            border-left: 1px solid #e4e7ed;
            .panel-head{
                width: 100%;
                display: flex;
                justify-content: space-between;
            }
            .buttons{
                margin-bottom: 0px;
                margin-top: 10px;
                .el-button{
                    width:90px;
                }
            }
        }
        .blue-color{
            color:#1890FF;
            cursor: pointer;
        }
        .icon{
            margin-right:4px;
        }
        .toolBox{
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #E5E7EC;
        padding: 12px 28px;
        position: fixed;
        bottom: 0;
        background: #fff;
        z-index: 10;
        margin-left: -20px;
        .toolBox-text{
            margin-left: 8px;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.65);
            span{
                margin:0 4px;
            }
        }
        .cancle-click{
            cursor: pointer;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #919398;
            margin-left: 32px;
        }
  }
  .toolBox-small{
      width: calc(100% - 210px);
  }
  .toolBox-midul{
      width: calc(100% - 54px);
  }
  .toolBox-large{
      width: 100%
  }
}
</style>
